/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.finance.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import com.lxk.finance.domain.bo.AccUserAccountBo;
import com.lxk.finance.domain.bo.AccUserAccountUpdateBo;
import com.lxk.finance.domain.vo.AccUserAccountVo;
import com.lxk.finance.service.IAccUserAccountService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户账户
 *
 * @author LXK-RY5
 * @date 2024-07-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/finance/userAccount")
public class AccUserAccountController extends BaseController {

    private final IAccUserAccountService accUserAccountService;


    /**
     * 增加或者减少用户账户
     */
    @SaCheckPermission("finance:userAccount:addOrReduce")
    @PutMapping("/addOrReduce/{ids}")
    public R<Boolean> addOrReduce(@PathVariable Long[] ids, @Validated @RequestBody AccUserAccountUpdateBo accUserAccountUpdateBo) {
        ArrayList<Long> userIdList = CollUtil.newArrayList(ids);
        BigDecimal amount = accUserAccountUpdateBo.getAmount();
        Integer accountType = accUserAccountUpdateBo.getAccountType();
        userIdList.forEach(userId -> {
            if (amount.compareTo(new BigDecimal("0")) > 0) {
                accUserAccountService.addAccount(userId, UserType.APP_USER.getUserType(), "", amount, AccUserAccountBo.AccountType.getByCode(accountType), "系统增加");
            }
            else {
                Boolean success = accUserAccountService.reduceAccount(userId, UserType.APP_USER.getUserType(), "",
                    amount.multiply(new BigDecimal("-1")),
                    AccUserAccountBo.AccountType.getByCode(accountType), "系统减少");
                if (BooleanUtil.isFalse(success)) {
                    throw new ServiceException("账户金额过少");
                }
            }
        });
        return R.ok();
    }


    /**
     * 查询用户账户列表
     */
    @SaCheckPermission("finance:userAccount:list")
    @GetMapping("/list")
    public TableDataInfo<AccUserAccountVo> list(AccUserAccountBo bo, PageQuery pageQuery) {
        return accUserAccountService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出用户账户列表
     */
    @SaCheckPermission("finance:userAccount:export")
    @Log(title = "用户账户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(AccUserAccountBo bo, HttpServletResponse response) {
        List<AccUserAccountVo> list = accUserAccountService.queryList(bo);
        ExcelUtil.exportExcel(list, "用户账户", AccUserAccountVo.class, response);
    }

    /**
     * 获取用户账户详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("finance:userAccount:query")
    @GetMapping("/{id}")
    public R<AccUserAccountVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(accUserAccountService.queryById(id));
    }

    /**
     * 新增用户账户
     */
    @SaCheckPermission("finance:userAccount:add")
    @Log(title = "用户账户", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody AccUserAccountBo bo) {
        return toAjax(accUserAccountService.insertByBo(bo));
    }

    /**
     * 修改用户账户
     */
    @SaCheckPermission("finance:userAccount:edit")
    @Log(title = "用户账户", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody AccUserAccountBo bo) {
        return toAjax(accUserAccountService.updateByBo(bo));
    }

    /**
     * 删除用户账户
     *
     * @param ids 主键串
     */
    @SaCheckPermission("finance:userAccount:remove")
    @Log(title = "用户账户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(accUserAccountService.deleteWithValidByIds(List.of(ids), true));
    }
}
